<script setup lang="ts">
import DrawerModal from "@/components/drawer-modal/index.vue";
import PasswordIcon from "@/components/icons/password-icon.vue";

import { nextTick, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useMessage } from "naive-ui";

import { useRequest } from "@/api/utils.ts";
import { verifyRoomPwd } from "@/api/module/room.api.ts";
import { ROOM_PASSWORD_PATTERN, ROOM_PASSWORD_PATTERN_TIP } from "@/pages/room/constant/validation-constants.ts";
import { ROOM_ROUTE_PATH } from "@/router/routes/room.route.ts";

import type { RoomSummaryModel } from "@/api/model/room.model.ts";

const router = useRouter();
const message = useMessage();

const props = defineProps<{
    room?: RoomSummaryModel
}>();

const emits = defineEmits<{
    (e: "close"): void
}>();

const inputRef = ref<HTMLInputElement>();
const password = ref("");

const { response, request } = useRequest(verifyRoomPwd);

watch(() => props.room, value => {
    if (!value) {
        // room参数为空后, 代表无需输入密码了, 隐藏modal并将密码框的内容清空
        password.value = "";
    } else {
        // 传递room参数后, 自动获取输入框焦点
        nextTick(() => {
            inputRef.value?.focus();
        });
    }
});

function handleJoin() {
    const room = props.room;
    if (!room) {
        return;
    }
    const rid = room.id;
    const pwd = password.value;
    if (!ROOM_PASSWORD_PATTERN.test(pwd)) {
        return message.warning(`密码格式错误(${ROOM_PASSWORD_PATTERN_TIP})`);
    }

    request({ rid, pwd }).then(() => {
        router.push({
            path: ROOM_ROUTE_PATH,
            query: { rid, pwd }
        });
    });
}

function handleClose() {
    emits("close");
}

</script>

<template>
    <drawer-modal :show="!!room" @update:show="value => !value && handleClose()" :mask-closeable="!response.waiting">
        <div class="flex flex-col gap-5 items-center">
            <h3 class="text-lg">请输入房间密码</h3>
            <n-input
                ref="inputRef"
                size="large"
                type="password"
                placeholder=""
                :disabled="response.waiting"
                v-model:value="password"
                @keydown.enter="handleJoin"
            >
                <template #prefix>
                    <n-icon :size="16"><password-icon/></n-icon>
                </template>
            </n-input>
            <n-button block size="large" type="primary" @click="handleJoin" :loading="response.waiting">加入</n-button>
        </div>
    </drawer-modal>
</template>

<style lang="scss" scoped>

</style>